<script setup lang="ts">
import { getHomeBanner, getHomeCategoryMutli, getHomeHotMutli } from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import skeleton from './components/skeleton.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { useGuessList } from '@/composables'

// 轮播图图片
const homeBannerList = ref<BannerItem[]>([])
// 分类菜单
const homeCategoryList = ref<CategoryItem[]>([])
//热门推荐
const homeHotList = ref<HotItem[]>([])

// 判断是否下拉刷新完毕
const isTriggered = ref(false)
// 判断是否加载中
const isLoading = ref(false)

// 轮播图图片
const getHomeBannerData = async () => {
  const res = await getHomeBanner()
  homeBannerList.value = res.result
}

// 分类菜单
const getHomeCategoryMutliData = async () => {
  const res = await getHomeCategoryMutli()
  homeCategoryList.value = res.result
}

//热门推荐
const getHomeHotMutliData = async () => {
  const res = await getHomeHotMutli()
  homeHotList.value = res.result
}

/**
 * 做会员中心时，把获取实例和触底事件封装在src/components/index.ts
 * 调用就行
 */

// XtxGuess实例
// const guessRef = ref<XtxGuessInstance>()

// 触底事件，调用子组件的函数
// const onScrolltolower = () => {
//   guessRef.value?.getGoodsData()
// }
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新事件
const onRefresherrefresh = async () => {
  isTriggered.value = true
  await Promise.allSettled([
    getHomeBannerData(),
    getHomeCategoryMutliData(),
    getHomeHotMutliData(),
    guessRef.value?.resetData(),
  ])
  isTriggered.value = false
}

onLoad(async () => {
  isLoading.value = true
  await Promise.allSettled([getHomeBannerData(), getHomeCategoryMutliData(), getHomeHotMutliData()])
  isLoading.value = false
})
</script>

<template>
  <CustomNavbar />
  <scroll-view
    @refresherrefresh="onRefresherrefresh"
    refresher-enabled
    @scrolltolower="onScrolltolower"
    :refresher-triggered="isTriggered"
    class="scroll"
    scroll-y
  >
    <skeleton v-if="isLoading" />
    <template v-else>
      <XtxSwiper :list="homeBannerList" />
      <CategoryPanel :list="homeCategoryList" />
      <HotPanel :list="homeHotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll {
  flex: 1;
}
</style>
